1986F - Non-academic Problem - CodeForces Solution


dfs and similar graphs

Please click on ads to support us..

Python Code:


from sys import *
input=lambda:stdin.readline().rstrip()

from types import GeneratorType
def bootstrap(f, stack=[]):
    def wrappedfunc(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        break
                    to = stack[-1].send(to)
            return to
    return wrappedfunc

def out(l):
    print(' '.join(map(str,l)))

def yes():
    print('Yes')

def no():
    print('No')

def alice():
    print('Alice')

def bob():
    print('Bob')

def vis(a):
        if v_a[a-1]==1:
        return True
    else:
        return False

@bootstrap              
def dfs(a,cnt,par=0):
            temp=adj_list[a-1]
    v_a[a-1]=1
    min_step[a]=cnt
    for i,j in enumerate(temp):
        if j==par:
            continue
        if not vis(j):
            yield dfs(j,cnt+1,a)
            min_step[a]=min(min_step[j],min_step[a])
            sub[a]+=sub[j]
            if min_step[j]>cnt:
                bridge.append(j)
        else:
            min_step[a]=min(min_step[j],min_step[a])
    sub[a]+=1
    yield
        
def solve():
    global v,e,v_a,adj_list,min_step,sub,bridge
        v,e=map(int,input().split())
    v_a=[0]*v
    sub=[0]*(v+1)
    bridge=[]
    min_step=[0]*(v+1)
    ans=v*(v-1)//2
    adj_list=[[] for i in range(v)]
    for i in range(e):
        x,y=map(int,input().split())
        adj_list[x-1].append(y)
        adj_list[y-1].append(x)
    dfs(1,1,0)
    for i,j in enumerate(bridge):
        ans=min(ans,sub[j]*(sub[j]-1)//2+(v-sub[j])*(v-sub[j]-1)//2)
    print(ans)

for _ in range(int(input())):
    solve()


Comments

Submit
0 Comments
More Questions

71. Simplify Path
62. Unique Paths
50. Pow(x, n)
43. Multiply Strings
34. Find First and Last Position of Element in Sorted Array
33. Search in Rotated Sorted Array
17. Letter Combinations of a Phone Number
5. Longest Palindromic Substring
3. Longest Substring Without Repeating Characters
1312. Minimum Insertion Steps to Make a String Palindrome
1092. Shortest Common Supersequence
1044. Longest Duplicate Substring
1032. Stream of Characters
987. Vertical Order Traversal of a Binary Tree
952. Largest Component Size by Common Factor
212. Word Search II
174. Dungeon Game
127. Word Ladder
123. Best Time to Buy and Sell Stock III
85. Maximal Rectangle
84. Largest Rectangle in Histogram
60. Permutation Sequence
42. Trapping Rain Water
32. Longest Valid Parentheses
Cutting a material
Bubble Sort
Number of triangles
AND path in a binary tree
Factorial equations
Removal of vertices